package com.scrumtrek.trainings.tdd;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: msuprunov
 * Date: 20.02.13
 * Time: 16:27
 * To change this template use File | Settings | File Templates.
 */
public class BookStoreService {
    IStore store;
    HashMap<String, ArrayList<Book>> authors, titles;

    public BookStoreService(IStore store) {
        this.store = store;
        authors = new HashMap<String, ArrayList<Book>>();
        titles = new HashMap<String, ArrayList<Book>>();
    }

    public void addBook(Book book) {
        store.addItem(book);

        String author = book.getAuthor(),
                title = book.getTitle();

        if (this.authors.get(author) == null) {
            ArrayList<Book> books = new ArrayList<Book>();
            books.add(book);
            this.authors.put(author, books);
        }
        else if(this.authors.get(author).indexOf(book) == -1) {
            this.authors.get(author).add(book);
        }

        if (this.titles.get(title) == null) {
            ArrayList<Book> books = new ArrayList<Book>();
            books.add(book);
            this.titles.put(title, books);
        }
        else if(this.titles.get(title).indexOf(book) == -1) {
            this.titles.get(title).add(book);
        }
    }

    public int getTotalBooksAmount() {
        return store.getCount();
    }

    public Set<String> getAuthors() {
        return authors.keySet();
    }

    public Set<String> getTitles() {
        HashSet<String> result = new HashSet<String>();

        for (ArrayList<Book> books : titles.values()) {
            for (Book book : books) {
                String str = new String();
                str = book.getTitle();
                if(book.getPublisher() != null) {
                    str += " [" + book.getPublisher() + "]";
                }
                if(book.getYear() != null) {
                    str += " [" + book.getYear() + "]";
                }
                result.add(str);
            }
        }

        return result;
    }

    public ArrayList<Book> findByAuthor(String author) {
        return authors.get(author);
    }

    public ArrayList<Book> findByTitle(String title) {
        return titles.get(title);
    }

    public boolean existBook(Book book){
        return store.existItem(book);
    }

    public void sellBook(Book book) {
        store.sellItem(book);
        ArrayList<Book> a = authors.get(book.getAuthor());
        a.remove(book);
        if(a.size() == 0) {
            authors.remove(book.getAuthor());
        }

        ArrayList<Book> t = titles.get(book.getTitle());
        t.remove(book);
        if(t.size() == 0) {
            titles.remove(book.getTitle());
        }
    }
}
